package com.karry.yl.web.financial;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.karry.commons.base.SuperController;
import com.karry.commons.util.TimeUtil;
import com.karry.commons.vo.LayTableResponse;
import com.karry.yl.domain.financial.Refund;
import com.karry.yl.service.financial.RefundService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * 退款记录Controller
 */

@Controller
@RequestMapping("/refund")
public class RefundController extends SuperController {

    private static final Logger log = LoggerFactory.getLogger(RefundController.class);
    @Autowired
    private RefundService refundService;

    @RequestMapping
    public String listUI() {
        return "financial/refund/list";
    }

    @RequestMapping("/add")
    public String addUI() {
        return "financial/refund/add";
    }

    @RequestMapping("edit")
    public String editUI(Long id, ModelMap map) {
        Refund refund = refundService.selectById(id);
        map.put("foodSampleModel", refund);
        return "financial/refund/edit";
    }


    @RequestMapping("/list")
    @ResponseBody
    public LayTableResponse listUI(int page, int limit, String userName) {
        Page<Refund> refund = null;
        if (StringUtils.isEmpty(userName)) {
            refund = refundService.selectPage(new Page<Refund>(page, limit), new EntityWrapper<Refund>().eq("orgId", currentUser.getOrgId()).orderBy("createdTime",false));
        } else {
            refund = refundService.selectPage(new Page<Refund>(page, limit), new EntityWrapper<Refund>().eq("orgId", currentUser.getOrgId()).like("userName", userName).orderBy("createdTime",false));
        }
        return new LayTableResponse(refund.getRecords(), refund.getTotal());
    }

    @RequestMapping("/save")
    public String save(Refund refund) {
        refund.setRefundUser(currentUser.getUserName());
        refund.setOrgId(currentUser.getOrgId());
        refundService.insert(refund);
        return "redirect:/refund";
    }

    @RequestMapping("/update")
    public String update(Refund refund) {
        refund.setRefundUser(currentUser.getUserName());
        refund.setOrgId(currentUser.getOrgId());
        refundService.updateById(refund);
        return "redirect:/refund";
    }

    /**
     * 删除
     *
     * @param
     * @return
     */
    @RequestMapping(path = "/delete")
    public String delete(@RequestParam("id") List<Long> ids) {
        refundService.deleteBatchIds(ids);
        return "redirect:/refund";
    }
 /**
     * 导出为excel
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping("/export/excel")
    public void exportExcel(HttpServletResponse response, String startDate, String endDate) {
        List<Refund> refunds = refundService.selectList(new EntityWrapper<Refund>().eq("orgId", currentUser.getOrgId()));
        //生成Excel,并存储临时文件
        // 创建一个HSSFWorkbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("退款记录");
        // 表头
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
        //声明列对象
        HSSFCell cell = null;
        //创建标题
        String[] title = {"老人姓名", "老人编号", "退款金额", "退款说明", "制作员"};
        for (int i = 0; i < title.length; i++) {
            row.setHeightInPoints(20);
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
            sheet.setColumnWidth(i, 21 * 256);
        }
        //创建内容
        for (int i = 0; i < refunds.size(); i++) {
            row = sheet.createRow(i + 1);
            row.setHeightInPoints(20);
            sheet.setColumnWidth(i + 1, 21 * 256);
            Refund refund = refunds.get(i);
            row.createCell(0).setCellValue(refund.getUserName());
            row.createCell(1).setCellValue(refund.getUserCode());
            row.createCell(2).setCellValue(refund.getRefundMoney());
            row.createCell(3).setCellValue(refund.getRefundRemark());
            row.createCell(4).setCellValue(refund.getRefundUser());
        }
        //下载
        response.setCharacterEncoding("UTF-8");
        try (ServletOutputStream out = response.getOutputStream();) {
            response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("退款记录-" + TimeUtil.format(new Date(), "yyyyMMddHHmmss") + ".xls", "UTF-8"));
            wb.write(out);
        } catch (IOException e) {
            //TODO 下载失败日志记录
        } finally {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
